package common

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
)

const (
	red    = "\033[31m"
	green  = "\033[32m"
	yellow = "\033[33m"
	blue   = "\033[34m"
	reset  = "\033[0m"
)

func RedPrintln(s string) {
	fmt.Println(red + s + reset)
}

func GreenPrintln(s string) {
	fmt.Println(green + s + reset)
}

func YellowPrintln(s string) {
	fmt.Println(yellow + s + reset)
}

func BluePrintln(s string) {
	fmt.Println(blue + s + reset)
}

// 输出不同颜色的文本
//fmt.Println(Red + "这是红色文本" + Reset)
//fmt.Println(Green + "这是绿色文本" + Reset)
//fmt.Println(Yellow + "这是黄色文本" + Reset)
//fmt.Println(Blue + "这是蓝色文本" + Reset)

func GetConfigFile() string {
	path := AbsoluteDir()
	conf := filepath.Join(path, "loadBalance.conf")
	return conf
}

func tailCut(s string, cut string) string {
	S := []rune(cut)
	D := []rune(s)

	var position int
	flag := true
	j := len(S)
	for i := len(D); i > 0; i-- {
		if '/' != D[i-1] && D[i-1] == S[j-1] {
			if flag {
				position = i
			}
			j--
			if 0 == j {
				j = len(S)
			}
			flag = false
		} else {
			flag = true
			if D[i-1] == '/' && j == len(S) && 0 != position {
				break
			}
		}
	}
	r := D[0:position]
	return string(r)
}

func AbsoluteDir() string {
	var path string
	execName := os.Args[0]

	OK := strings.Contains(execName, "go_build_")
	if !OK {
		path = filepath.Dir(execName)
	} else {
		_, f, _, ok := runtime.Caller(0)
		if ok {
			regStr := `_([^_.]+)(\.exe){0,1}$`
			compile := regexp.MustCompile(regStr)
			subMatch := compile.FindSubmatch([]byte(execName))
			tail := string(subMatch[1])

			p := filepath.Dir(f)
			path = tailCut(p, tail)
		}
	}
	return path
}
